package com.phei.netty.broadcast;

import java.net.InetSocketAddress;
import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.util.CharsetUtil;

public class LogEventEncoder extends MessageToMessageEncoder<LogEvent> {

	private  InetSocketAddress remoteAddress = null;
	
	
	public LogEventEncoder(InetSocketAddress remoteAddress) {
		this.remoteAddress = remoteAddress;
		
	}


	@Override
	protected void encode(ChannelHandlerContext ctx, LogEvent logEvent, List<Object> out) throws Exception {
		byte[]  file = logEvent.getLogfile().getBytes(CharsetUtil.UTF_8);
		byte[] msg = logEvent.getMsg().getBytes(CharsetUtil.UTF_8);
		ByteBuf buf = ctx.alloc().buffer(file.length + msg.length + 1);
		buf.writeBytes(file);
		buf.writeByte(LogEvent.SEPARATOR);
		buf.writeBytes(msg);
		//DatagramPacket data = new DatagramPacket(msg, msg.length, remoteAddress);
		
		out.add(new DatagramPacket(buf, remoteAddress));
		//out.add(data);
		//out.add(new DatagramPacket(msg,remoteAddress));
		//out.add(ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap(logEvent.getMsg()),CharsetUtil.UTF_8));  
	}

}
